package com.basis.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * druid数据源配置
 */
@Configuration
public class DruidConfig {

	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druidDataSource() {
		return new DruidDataSource();
	}

	/**
	 * 主要实现WEB监控的配置处理
	 */
	@Bean
	public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
		ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(
				new StatViewServlet(), "/druid/*");
		// 白名单,多个用逗号分割， 如果allow没有配置或者为空，则允许所有访问
		// servletRegistrationBean.addInitParameter("allow", "");
		// 黑名单,多个用逗号分割 (共同存在时，deny优先于allow)
		// servletRegistrationBean.addInitParameter("deny", "192.168.1.110");

		Map<String, String> initParams = new HashMap<>();
		initParams.put("loginUsername", "admin");
		initParams.put("loginPassword", "admin");
		servletRegistrationBean.setInitParameters(initParams);
		return servletRegistrationBean;
	}

	@Bean
	public FilterRegistrationBean<WebStatFilter> druidWebStatFilter() {
		FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(
				new WebStatFilter());
		Map<String, String> initParams = new HashMap<>();
		//添加不需要忽略的格式信息
		initParams.put("exclusions", "*.js,*.css,/druid/*");
		filterRegistrationBean.setInitParameters(initParams);
		//所有请求进行监控处理
		filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
		return filterRegistrationBean;
	}
}
